﻿using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using System;

public class Item : MonoBehaviour, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler, IBeginDragHandler, IDragHandler,IEndDragHandler
{
    public ItemInfo Info { private set; get; }
    public int GridIdx { private set; get; }


    public static Action<Transform, string> OnEnter;
    public static Action OnExit;

    private Sprite itemIcon;
    private Image itemIconImg;
    private static Sprite InitSprite;

    private static Transform canvasTra;
    private Transform oldParent;
    private Vector3 oloPos;


    public void Init(int index)
    {
        GridIdx = index;
        if (InitSprite == null)
            InitSprite = GetComponent<Image>().sprite;
        itemIconImg = GetComponent<Image>();
    }

    public void SetItemInfo(ItemInfo info)
    {
        Info = info;
        if (Info == null)
        {//清理还原格子
            itemIcon = InitSprite;
            itemIconImg.sprite = itemIcon;
            return;
        }
        itemIcon = Resources.Load(Info.ItemImgRes, typeof(Sprite)) as Sprite;
        itemIconImg.sprite = itemIcon;
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        if (eventData.clickCount == 2 && Info != null)
            Mgr.bagMgr.ReqUseItem(Info, 1);
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        OnExit?.Invoke();
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        if(Info != null)
            OnEnter?.Invoke(transform, Info.ItemDsc);
    }

    public void OnBeginDrag(PointerEventData eventData)
    {//开始拖动
        if (canvasTra == null)
            canvasTra = Mgr.panelMgr.ParentCanvas.transform;
        oldParent = transform.parent;
        transform.SetParent(canvasTra);
        oloPos = transform.position;
        gameObject.GetComponent<Image>().raycastTarget = false;
    }

    public void OnDrag(PointerEventData eventData)
    {
        transform.position = Mgr.panelMgr.UICamera.ScreenToWorldPoint(Input.mousePosition);
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        transform.SetParent(oldParent);
        transform.position = oloPos;
        GameObject go = eventData.pointerCurrentRaycast.gameObject;
        if(go != null && go.GetComponent<Item>() != null)
        {
            Mgr.bagMgr.ReqMoveItem(Info, go.GetComponent<Item>().GridIdx);
        }
        gameObject.GetComponent<Image>().raycastTarget = true;
    }

    private void SetParentAndPosition()
    {

    }
}